<template>
	<view class="container">
		<view class="goods-section">
			<view class="g-header">
				<text class="name">商品评价</text>
			</view>
			<view class="g-item">
				<image :src="orderItem.productPic" class="goods-img"></image>
				<view class="right">
					<text class="title clamp">{{orderItem.productName}}</text>
					<text class="spec">{{formatProductAttr(orderItem.productAttr)}}</text>
					<view class="price-box">
						<text class="price">￥{{orderItem.productPrice}}</text>
						<text class="number">x {{orderItem.productQuantity}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="evaluate-box">
			<view class="item">
				<text class="label">商品满意度</text>
				<view class="rating-box">
					<text class="yticon icon-xingxing" 
						v-for="(star, index) in 5" 
						:key="index" 
						:class="{'active': index < rating}"
						@click="setRating(index + 1)"></text>
					<text class="rating-text">{{getRatingText()}}</text>
				</view>
			</view>
			<view class="item">
				<text class="label">评价内容</text>
				<textarea v-model="content" class="textarea" placeholder="请输入您对商品的评价，不少于10个字" placeholder-class="placeholder" />
			</view>
			<view class="item">
				<text class="label">上传图片 (最多3张)</text>
				<view class="upload-box">
					<view class="upload-item" v-for="(img, index) in images" :key="index">
						<image :src="img" mode="aspectFill"></image>
						<text class="yticon icon-fork" @click="deleteImage(index)"></text>
						
						<!-- 上传进度指示器 -->
						<view class="upload-progress" v-if="uploadingIndex === index">
							<view class="progress-bar">
								<view class="progress-inner" :style="{width: uploadProgress + '%'}"></view>
							</view>
							<text class="progress-text">{{uploadProgress}}%</text>
						</view>
					</view>
					<view class="upload-btn" @click="chooseImage" v-if="images.length < 3">
						<text class="yticon icon-photograph"></text>
						<text class="upload-text">上传图片</text>
					</view>
				</view>
				<text class="tips">支持JPG、PNG格式图片，单张不超过2MB</text>
			</view>
		</view>
		
		<view class="anonymous-box">
			<text>匿名评价</text>
			<switch :checked="isAnonymous" @change="switchChange" color="#fa436a" />
		</view>
		
		<button class="submit-btn" @click="submitEvaluate">提交评价</button>
	</view>
</template>

<script>
	import {
		formatDate
	} from '@/utils/date';
	import { createComment } from '@/api/comment.js';
	import { fetchOrderDetail, getOrderItemDetail } from '@/api/order.js';
	import { uploadFileToMinio } from '@/utils/minioUtil.js';

	export default {
		data() {
			return {
				orderId: null,
				orderItemId: null,
				orderItem: {},
				rating: 5, // 默认5星
				content: '',
				images: [],
				isAnonymous: false,
				submitting: false,
				uploadedImgUrls: [],
				productAttribute: '',
				uploadProgress: 0,
				uploadingIndex: -1, // 当前正在上传的图片索引
				uploading: false    // 是否有图片正在上传
			}
		},
		onLoad(options) {
			if (options.orderId) {
				this.orderId = options.orderId;
			}
			if (options.orderItemId) {
				this.orderItemId = options.orderItemId;
			}
			this.loadOrderItemData();
		},
		methods: {
			// 格式化商品属性
			formatProductAttr(jsonAttr) {
				try {
					if (!jsonAttr) return '';
					
					let attrArr = typeof jsonAttr === 'string' ? JSON.parse(jsonAttr) : jsonAttr;
					if (!Array.isArray(attrArr)) return jsonAttr;
					
					let attrStr = '';
					for (let attr of attrArr) {
						if (attr.key && attr.value) {
							attrStr += attr.key + ":" + attr.value + ";";
						}
					}
					
					// 保存格式化后的属性字符串，用于提交评价
					this.productAttribute = attrStr.replace(/;$/g, '');
					
					return attrStr;
				} catch (e) {
					console.error('格式化商品属性失败:', e);
					return jsonAttr;
				}
			},
			
			// 加载订单商品数据
			loadOrderItemData() {
				// 显示加载中的状态
				this.orderItem = {
					productName: '商品名称加载中...',
					productPic: '/static/img/loading.png',
					productPrice: 0,
					productQuantity: 1,
					productAttr: '[]'
				};
				
				// 尝试从本地缓存获取订单商品信息
				const cachedItem = uni.getStorageSync('currentOrderItem');
				if (cachedItem) {
					try {
						this.orderItem = JSON.parse(cachedItem);
						console.log('从缓存加载订单商品:', this.orderItem);
						this.formatProductAttr(this.orderItem.productAttr);
						return; // 如果从缓存加载成功，直接返回
					} catch (e) {
						console.error('解析缓存订单商品信息失败:', e);
					}
				}
				
				// 如果有orderItemId，优先使用getOrderItemDetail API获取详细信息
				if (this.orderItemId) {
					uni.showLoading({
						title: '加载商品信息...'
					});
					
					getOrderItemDetail(this.orderItemId).then(response => {
						uni.hideLoading();
						if (response.code === 200 && response.data) {
							this.orderItem = response.data;
							this.formatProductAttr(this.orderItem.productAttr);
							
							// 缓存订单商品信息
							uni.setStorageSync('currentOrderItem', JSON.stringify(this.orderItem));
						} else {
							this.fallbackToOrderDetail();
						}
					}).catch(err => {
						console.error('获取订单商品详情失败:', err);
						uni.hideLoading();
						// 失败后尝试获取整个订单详情
						this.fallbackToOrderDetail();
					});
				} else if (this.orderId) {
					this.fallbackToOrderDetail();
				} else {
					uni.showToast({
						title: '缺少订单信息，无法加载商品',
						icon: 'none'
					});
				}
			},
			
			// 回退到获取整个订单详情的方法
			fallbackToOrderDetail() {
				if (!this.orderId) {
					uni.showToast({
						title: '订单ID不存在',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '加载订单信息...'
				});
				
				fetchOrderDetail(this.orderId).then(response => {
					uni.hideLoading();
					if (response.code === 200 && response.data) {
						// 成功获取到订单信息
						const orderDetail = response.data;
						
						// 查找对应的订单商品项
						if (orderDetail.orderItemList && orderDetail.orderItemList.length > 0) {
							// 如果有指定orderItemId，则查找对应商品项
							if (this.orderItemId) {
								const matchedItem = orderDetail.orderItemList.find(item => item.id == this.orderItemId);
								if (matchedItem) {
									this.orderItem = matchedItem;
								} else {
									// 如果找不到指定商品项，使用第一个
									this.orderItem = orderDetail.orderItemList[0];
									this.orderItemId = this.orderItem.id;
								}
							} else {
								// 没有指定商品项ID，默认使用第一个
								this.orderItem = orderDetail.orderItemList[0];
								this.orderItemId = this.orderItem.id;
							}
							
							// 处理商品属性
							this.formatProductAttr(this.orderItem.productAttr);
							
							// 缓存获取到的订单商品信息
							uni.setStorageSync('currentOrderItem', JSON.stringify(this.orderItem));
						} else {
							uni.showToast({
								title: '订单中没有商品信息',
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: response.message || '获取订单信息失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取订单信息失败:', err);
					uni.showToast({
						title: '获取订单信息失败，请返回重试',
						icon: 'none'
					});
				});
			},
			
			// 获取评分对应的文字描述
			getRatingText() {
				switch(this.rating) {
					case 1: return '非常差';
					case 2: return '较差';
					case 3: return '一般';
					case 4: return '满意';
					case 5: return '非常满意';
					default: return '';
				}
			},
			
			// 设置评分
			setRating(rating) {
				this.rating = rating;
			},
			
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 3 - this.images.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 检查文件大小，限制为2MB
						const validFiles = res.tempFiles.filter(file => {
							if (file.size > 2 * 1024 * 1024) {
								uni.showToast({
									title: '图片大小不能超过2MB',
									icon: 'none'
								});
								return false;
							}
							return true;
						});
						
						if (validFiles.length === 0) return;
						
						// 将选择的图片添加到预览列表
						const validPaths = validFiles.map(file => file.path);
						this.images = [...this.images, ...validPaths];
						
						// 上传图片
						this.uploadImages(validPaths);
					}
				});
			},
			
			// 上传图片
			uploadImages(tempFilePaths) {
				if (tempFilePaths.length === 0) return;
				
				this.uploading = true;
				
				// 一次上传一张图片
				const uploadSequentially = (index = 0) => {
					if (index >= tempFilePaths.length) {
						this.uploading = false;
						this.uploadingIndex = -1;
						return;
					}
					
					const filePath = tempFilePaths[index];
					this.uploadingIndex = this.images.indexOf(filePath);
					
					uni.showLoading({
						title: `上传图片 ${index+1}/${tempFilePaths.length}...`
					});
					
					// 使用MinIO工具类上传文件
					uploadFileToMinio(filePath, (progress) => {
						this.uploadProgress = progress;
					}).then(result => {
						console.log('MinIO上传成功:', result);
						// 储存上传成功的图片URL
						this.uploadedImgUrls.push(result.url);
						
						// 继续上传下一张
						setTimeout(() => {
							uni.hideLoading();
							uploadSequentially(index + 1);
						}, 500);
					}).catch(error => {
						console.error('上传失败:', error);
						uni.hideLoading();
						uni.showToast({
							title: error.message || '上传图片失败',
							icon: 'none'
						});
						
						// 从预览列表中移除上传失败的图片
						const failedIndex = this.images.indexOf(filePath);
						if (failedIndex !== -1) {
							this.images.splice(failedIndex, 1);
						}
						
						// 继续上传下一张
						setTimeout(() => {
							uploadSequentially(index + 1);
						}, 1000);
					});
				};
				
				// 开始顺序上传
				uploadSequentially();
			},
			
			// 删除图片
			deleteImage(index) {
				// 如果正在上传这张图片，提示用户
				if (this.uploadingIndex === index) {
					uni.showToast({
						title: '图片正在上传，请稍候',
						icon: 'none'
					});
					return;
				}
				
				// 删除预览图片
				this.images.splice(index, 1);
				// 删除对应的已上传URL
				if (this.uploadedImgUrls.length > index) {
					this.uploadedImgUrls.splice(index, 1);
				}
			},
			
			// 匿名评价开关
			switchChange(e) {
				this.isAnonymous = e.detail.value;
			},
			
			// 提交评价
			submitEvaluate() {
				if (this.submitting) return;
				
				if (this.content.length < 10) {
					uni.showToast({
						title: '评价内容不能少于10个字',
						icon: 'none'
					});
					return;
				}
				
				// 检查是否有上传中的图片
				if (this.uploading) {
					uni.showToast({
						title: '图片正在上传，请稍候',
						icon: 'none'
					});
					return;
				}
				
				this.submitting = true;
				uni.showLoading({
					title: '提交中...'
				});
				
				// 构建评价参数
				const commentParam = {
					productId: this.orderItem.productId,
					orderId: this.orderId,
					orderItemId: this.orderItemId,
					productName: this.orderItem.productName,
					star: this.rating,
					content: this.content,
					productAttribute: this.productAttribute,
					member: {
						anonymous: this.isAnonymous ? 1 : 0
					}
				};
				
				// 如果有上传的图片，添加到参数中
				if (this.uploadedImgUrls.length > 0) {
					commentParam.pics = this.uploadedImgUrls.join(',');
				}
				
				console.log('提交评价参数:', commentParam);
				
				// 调用API提交评价
				createComment(commentParam).then(response => {
					uni.hideLoading();
					this.submitting = false;
					
					if (response.code === 200) {
						uni.showToast({
							title: '评价提交成功',
							icon: 'success'
						});
						
						// 清理缓存的评价数据
						uni.removeStorageSync('currentOrderItem');
						
						// 提交成功后返回订单列表页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: response.message || '评价提交失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					console.error('提交评价失败:', error);
					uni.hideLoading();
					this.submitting = false;
					
					uni.showToast({
						title: '评价提交失败，请稍后重试',
						icon: 'none'
					});
				});
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding: 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
	}
	
	.goods-section {
		background: #fff;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		
		.g-header {
			display: flex;
			align-items: center;
			height: 84rpx;
			padding: 0 30rpx;
			
			.name {
				font-size: 30rpx;
				color: $font-color-dark;
			}
		}
		
		.g-item {
			display: flex;
			padding: 20rpx 30rpx;
			
			.goods-img {
				display: block;
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
			}
			
			.right {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding-left: 24rpx;
				overflow: hidden;
				
				.title {
					font-size: 28rpx;
					color: $font-color-dark;
					line-height: 40rpx;
				}
				
				.spec {
					font-size: 24rpx;
					color: $font-color-light;
					margin-top: 12rpx;
				}
				
				.price-box {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-top: auto;
					
					.price {
						font-size: 30rpx;
						color: $font-color-dark;
					}
					
					.number {
						font-size: 26rpx;
						color: $font-color-light;
					}
				}
			}
		}
	}
	
	.evaluate-box {
		background: #fff;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		padding: 20rpx 30rpx;
		
		.item {
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f8f8f8;
			
			&:last-child {
				border-bottom: none;
			}
			
			.label {
				display: block;
				font-size: 28rpx;
				color: $font-color-dark;
				margin-bottom: 20rpx;
			}
			
			.rating-box {
				display: flex;
				align-items: center;
				
				.yticon {
					font-size: 48rpx;
					color: #ccc;
					margin-right: 20rpx;
					
					&.active {
						color: #FFB400;
					}
				}
				
				.rating-text {
					font-size: 28rpx;
					color: #FFB400;
					margin-left: 20rpx;
				}
			}
			
			.textarea {
				width: 100%;
				height: 200rpx;
				font-size: 28rpx;
				color: $font-color-dark;
				background: #f8f8f8;
				border-radius: 8rpx;
				padding: 20rpx;
				box-sizing: border-box;
			}
			
			.placeholder {
				color: #bbb;
			}
			
			.upload-box {
				display: flex;
				flex-wrap: wrap;
				
				.upload-item, .upload-btn {
					width: 200rpx;
					height: 200rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					position: relative;
					border-radius: 8rpx;
					overflow: hidden;
					box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
				}
				
				.upload-item {
					image {
						width: 100%;
						height: 100%;
					}
					
					.yticon {
						position: absolute;
						right: 0;
						top: 0;
						width: 44rpx;
						height: 44rpx;
						line-height: 44rpx;
						text-align: center;
						background: rgba(0,0,0,0.6);
						color: #fff;
						font-size: 24rpx;
						z-index: 10;
					}
					
					.upload-progress {
						position: absolute;
						left: 0;
						bottom: 0;
						width: 100%;
						background: rgba(0,0,0,0.6);
						padding: 10rpx;
						
						.progress-bar {
							width: 100%;
							height: 10rpx;
							background: rgba(255,255,255,0.3);
							border-radius: 10rpx;
							overflow: hidden;
							
							.progress-inner {
								height: 100%;
								background: #fff;
								border-radius: 10rpx;
							}
						}
						
						.progress-text {
							color: #fff;
							font-size: 20rpx;
							text-align: center;
							margin-top: 5rpx;
						}
					}
				}
				
				.upload-btn {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					background: #f8f8f8;
					border: 1px dashed #ddd;
					
					.yticon {
						font-size: 60rpx;
						color: #bbb;
						margin-bottom: 10rpx;
					}
					
					.upload-text {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
			
			.tips {
				font-size: 24rpx;
				color: #999;
				margin-top: 10rpx;
				display: block;
			}
		}
	}
	
	.anonymous-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #fff;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		color: $font-color-dark;
	}
	
	.submit-btn {
		background: $uni-color-primary;
		color: #fff;
		border-radius: 50rpx;
		font-size: 32rpx;
		height: 90rpx;
		line-height: 90rpx;
		margin-top: 40rpx;
	}
</style> 